// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const userId = wxContext.OPENID
  
  try {
    // 获取用户信息和周期信息，用于个性化推荐
    const userRes = await db.collection('users')
      .where({
        _id: userId
      })
      .get()
    
    const user = userRes.data[0] || {}
    
    // 从event获取参数
    const { cyclePhase = null, limit = 5 } = event
    
    // 构建查询条件
    let queryCondition = {}
    
    // 如果有周期阶段信息，优先推荐相关内容
    if (cyclePhase) {
      queryCondition.cycle_phase = cyclePhase
    }
    
    // 如果有用户生日信息，获取年龄段
    let ageGroup = null
    if (user.birthdate) {
      const birthDate = new Date(user.birthdate)
      const today = new Date()
      const age = today.getFullYear() - birthDate.getFullYear()
      
      if (age < 18) {
        ageGroup = "teen"
      } else if (age < 25) {
        ageGroup = "young-adult"
      } else if (age < 40) {
        ageGroup = "adult"
      } else {
        ageGroup = "mature"
      }
      
      // 添加年龄段过滤，使用数组包含查询
      if (ageGroup) {
        queryCondition.age_group = _.all([ageGroup])
      }
    }
    
    // 查询知识文章
    let knowledgeQuery = db.collection('knowledge')
    
    // 如果有过滤条件则应用
    if (Object.keys(queryCondition).length > 0) {
      knowledgeQuery = knowledgeQuery.where(queryCondition)
    }
    
    // 优先返回精选文章
    const knowledgeRes = await knowledgeQuery
      .orderBy('is_featured', 'desc')
      .orderBy('publish_date', 'desc')
      .limit(limit)
      .get()
    
    return {
      status: 'success',
      data: knowledgeRes.data || []
    }
  } catch (err) {
    return {
      status: 'error',
      message: err.message,
      error: err
    }
  }
} 